package com.mjf.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.mjf.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * 用户跳出详情(FlinkCEP)
 *   1.用户访问了第一个页面（last_page_id 为空）后，在一段时间之内（程序内为10s，可自定义）没有后续访问行为。
 *   2.用户访问了第一个页面（last_page_id 为空）后，在一段时间之内（程序内为10s，可自定义）再一次出现了访问第一个页面的行为（last_page_id 为空），这说明第一次访问之后跳出了。
 *
 * 跳出：跳出就是用户成功访问了网站的一个页面后就退出，不在继续访问网站的其它页面。而跳出率就是用跳出次数除以访问次数。
 *
 * 注意：这个程序由于需要判断一段时间之内的行为，所以会有延迟！！！
 *
 * 数据流向：web/app -> nginx -> springboot -> kafka(ods) -> flinkApp -> kafka(dwd) -> flinkApp -> kafka(dwm)
 * 程序：gmall2020-mock-log-2020-12-18.jar -> flink-logger.sh(包含 nginx/springboot/kafka(ods)) -> BaseLogApp(包含 flinkApp/kafka(dwd)) -> UserJumpDetailApp(包含 flinkApp/kafka(dwm))
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {

        // 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

/*
        // 测试时关闭
        // 设置状态后端
        env.setStateBackend(new FsStateBackend("hdfs://hadoop102:9000/gmall-flink/checkpoint"));
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(10000L);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);

        // 设置重启策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 10));
*/

        // 2.读取 Kafka dwd_page_log 主题数据
        String groupId = "UserJumpDetailApp";
        String sourceTopic = "dwd_page_log";
        String sinkTopic = "dwm_user_jump_detail";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getKafkaConsumer(sourceTopic, groupId));

        // 3.将每行数据转换为 Json 对象，并提取时间戳生成 watermark
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                                .withTimestampAssigner(
                                        new SerializableTimestampAssigner<JSONObject>() {
                                            @Override
                                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                                return element.getLong("ts");
                                            }
                                        })
                );

        // 4.定义模式序列
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("start")
                .where(new IterativeCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject, Context<JSONObject> context) throws Exception {
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() <= 0;
                    }
                })
                .next("next")
                .where(new IterativeCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject, Context<JSONObject> context) throws Exception {
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() <= 0;
                    }
                })
                .within(Time.seconds(10));

        // 使用循环模式定义序列
/*        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("start")
                .where(new IterativeCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject, Context<JSONObject> context) throws Exception {
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() <= 0;
                    }
                })
                .times(2)
                .consecutive()  // 指定严格近邻(next)
                .within(Time.seconds(10));*/

        // 5.将模式序列作用到流上
        PatternStream<JSONObject> patternStream = CEP.pattern(
                jsonObjDS.keyBy(json -> json.getJSONObject("common").getString("mid")),
                pattern
        );

        // 6.提取匹配上的和超时事件(第一个事件匹配上，第二个事件没来)
        OutputTag<JSONObject> timeOutTag = new OutputTag<JSONObject>("time-out") {
        };

        SingleOutputStreamOperator<JSONObject> selectDS = patternStream.select(
                timeOutTag,
                new PatternTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject timeout(Map<String, List<JSONObject>> map, long l) throws Exception {
                        return map.get("start").get(0);
                    }
                },
                new PatternSelectFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject select(Map<String, List<JSONObject>> map) throws Exception {
                        return map.get("start").get(0);
                    }
                }
        );

        DataStream<JSONObject> timeOutDS = selectDS.getSideOutput(timeOutTag);

        // 7.union 两种事件
        DataStream<JSONObject> unionDS = selectDS.union(timeOutDS);

        // 8.将数据写入 Kafka
        unionDS.print();
        unionDS.map(JSONAware::toJSONString).addSink(MyKafkaUtil.getKafkaProducer(sinkTopic));

        // 9.启动任务
        env.execute(UserJumpDetailApp.class.getName());

    }
}
